package com.xialuo.study.tools;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
public class PlanningTool {
    // 存储所有计划
    private final Map<String, Plan> plans = new HashMap<>();
    // 当前活动计划ID
    private String currentPlanId;

    @Tool(description = "创建新的分析计划")
    public String createPlan(
            @ToolParam(description = "计划ID") String planId,
            @ToolParam(description = "计划标题") String title,
            @ToolParam(description = "计划步骤列表") List<String> steps
    ) {
        if (plans.containsKey(planId)) {
            throw new RuntimeException("计划ID已存在: " + planId);
        }
        if(StringUtils.isEmpty(planId)||!planId.startsWith("plan_")){
            planId = "plan_" + System.currentTimeMillis();
        }
        Plan plan = new Plan(planId, title, steps);
        plans.put(planId, plan);
        currentPlanId = planId;
        return formatPlan(plan);
    }

    @Tool(description = "获取指定计划的详细信息")
    public String getPlan(
            @ToolParam(description = "计划ID，如果为空则返回当前活动计划") String planId
    ) {
        String targetPlanId = planId != null ? planId : currentPlanId;
        if (targetPlanId == null) {
            throw new RuntimeException("没有活动计划，请指定计划ID");
        }
        Plan plan = plans.get(targetPlanId);
        if (plan == null) {
            throw new RuntimeException("找不到计划: " + targetPlanId);
        }
        return formatPlan(plan);
    }

    @Tool(description = "更新步骤状态")
    public String updateStepStatus(
            @ToolParam(description = "计划ID，如果为空则使用当前活动计划") String planId,
            @ToolParam(description = "步骤索引(从0开始)") int stepIndex,
            @ToolParam(description = "步骤状态(NOT_STARTED, IN_PROGRESS, COMPLETED, BLOCKED)") String status
    ) {
        String targetPlanId = planId != null ? planId : currentPlanId;
        if (targetPlanId == null) {
            throw new RuntimeException("没有活动计划，请指定计划ID");
        }
        Plan plan = plans.get(targetPlanId);
        if (plan == null) {
            throw new RuntimeException("找不到计划: " + targetPlanId);
        }
        plan.updateStepStatus(stepIndex, StepStatus.valueOf(status));
        return formatPlan(plan);
    }

    @Tool(description = "列出所有计划")
    public String listPlans() {
        if (plans.isEmpty()) {
            return "没有可用的计划。";
        }

        StringBuilder output = new StringBuilder("可用的计划:\n");
        for (Plan plan : plans.values()) {
            String currentMarker = plan.getPlanId().equals(currentPlanId) ? " (当前活动)" : "";
            int completed = plan.getCompletedStepsCount();
            int total = plan.getSteps().size();
            output.append(String.format("• %s%s: %s - %d/%d 步骤已完成\n",
                    plan.getPlanId(), currentMarker, plan.getTitle(), completed, total));
        }
        return output.toString();
    }

    private String formatPlan(Plan plan) {
        StringBuilder output = new StringBuilder();
        output.append(String.format("计划: %s (ID: %s)\n", plan.getTitle(), plan.getPlanId()));
        output.append("=".repeat(output.length())).append("\n\n");

        // 计算进度统计
        int totalSteps = plan.getSteps().size();
        int completed = plan.getCompletedStepsCount();
        double percentage = totalSteps > 0 ? (completed * 100.0 / totalSteps) : 0.0;

        output.append(String.format("进度: %d/%d 步骤完成 (%.1f%%)\n", completed, totalSteps, percentage));
        output.append("\n步骤:\n");

        // 添加每个步骤的状态
        List<String> steps = plan.getSteps();
        List<StepStatus> statuses = plan.getStepStatuses();
        for (int i = 0; i < steps.size(); i++) {
            String statusSymbol = getStatusSymbol(statuses.get(i));
            output.append(String.format("%d. %s %s\n", i, statusSymbol, steps.get(i)));
        }

        return output.toString();
    }

    private String getStatusSymbol(StepStatus status) {
        return switch (status) {
            case NOT_STARTED -> "[ ]";
            case IN_PROGRESS -> "[→]";
            case COMPLETED -> "[✓]";
            case BLOCKED -> "[!]";
        };
    }

    // 内部类和枚举定义
    private static class Plan {
        private final String planId;
        private final String title;
        private final List<String> steps;
        private final List<StepStatus> stepStatuses;

        public Plan(String planId, String title, List<String> steps) {
            this.planId = planId;
            this.title = title;
            this.steps = new ArrayList<>(steps);
            this.stepStatuses = new ArrayList<>(Collections.nCopies(steps.size(), StepStatus.NOT_STARTED));
        }

        public String getPlanId() {
            return planId;
        }

        public String getTitle() {
            return title;
        }

        public List<String> getSteps() {
            return steps;
        }

        public List<StepStatus> getStepStatuses() {
            return stepStatuses;
        }

        public void updateStepStatus(int stepIndex, StepStatus status) {
            if (stepIndex < 0 || stepIndex >= steps.size()) {
                throw new RuntimeException("无效的步骤索引: " + stepIndex);
            }
            stepStatuses.set(stepIndex, status);
        }

        public int getCompletedStepsCount() {
            return (int) stepStatuses.stream()
                    .filter(status -> status == StepStatus.COMPLETED)
                    .count();
        }
    }

    private enum StepStatus {
        NOT_STARTED,
        IN_PROGRESS,
        COMPLETED,
        BLOCKED
    }
}
